import GameUtil from './GameUtil';
import TtUtil from './TtUtil';
// import UIHelper from '../../Game/UIHelper';

var ws : WebSocket = null;

export default class WebSocketUtil {
    static socketOpen: boolean = false;             //是否链接成功
    static reconnectInterval: any;
    static heartCount: number = 0;
    static heartInterval: any;
    static heartBeatTimer = null;               //心跳计时器id
    static openId : string = null;
    static rigistBack = null;

    static getUrl() {
        // return 'ws://192.168.0.198:12345?openId=' + this.openId;
        return 'ws://ws.meappstore.top?openId='+this.openId;
    }

    //链接socket
    static connectSocket(back?) {
        let self = this;
        this.rigistBack = back;
        this.openId = ReadLocal('usid','1');
        ws = new WebSocket(self.getUrl());//, null, cc.url.raw('resources/raw/215072411660467.pem'));
        ws.binaryType = "arraybuffer";
        ws.onopen = (event) => {
            Log('===========WebSocket onSocketOpen')
            self.socketOpen = true;
            clearInterval(self.heartBeatTimer);
            //开始心跳
            self.requestHeartBeat();
            self.heartBeatTimer = self.sendServerFlag();
            back && back(true);
        };

        ws.onmessage = (event) => {
            // console.log('============收到返回数据：',JSON.stringify(event));
            // Log('===========WebSocket onSocketClose')
            self.handleOnMessage(event);
        };

        ws.onerror = (event) => {
            self.socketOpen = false;
            clearInterval(self.heartBeatTimer);
            self.heartBeatTimer = null;
            // self.reconnection();
            Log('===========WebSocket onSocketError: ' + JSON.stringify(event))
            TtUtil.showWxText('连接服务器失败', 1, 2000);
            setTimeout(()=>{
                back && back(false);
            },1000)

        };
        ws.onclose = (event) => {
            Log('===========WebSocket onSocketClose: ' + JSON.stringify(event))
            self.socketOpen = false;
            clearInterval(self.heartBeatTimer);
            self.heartBeatTimer = null;
            // self.reconnection();
        };

    }
    static closeSocket(){
        if (ws){
            ws.close();
        }
    }

    //处理接受到的数据
    static handleOnMessage(event) {
        let self = this;
        var msg = event.data;
        cc.find('Canvas').emit('Socket', msg);
    }

    /**
     * 发送长连接消息
     */
    static sendSocketMessage(msg) {
        if (this.socketOpen && ws && ws.readyState === WebSocket.OPEN) {
            ws.send(msg);
            Log('发送消息:',msg)
        }
        else{
            TtUtil.hideLoading();
            // UIHelper.addClearPop('已与服务器断开连接',()=>{
            //     GameUtil.gotoSceneByPage('MainScene');
            // })
        }
    }
    static requestHeartBeat() {
        let param = {
            type : 1,                 
            openId : this.openId,         
            // roomId : 1,                 
            timestamp : new Date().getTime(),
            // messageCode : this.heartCount+'',
        }
        WebSocketUtil.sendSocketMessage('0');
        this.heartCount++ ;
    }
    /**
     * 同服务器测试心跳
     */
    static sendServerFlag() {
        // if (this.heartBeatTimer) {
        //     return this.heartBeatTimer;
        // }
        let id = setInterval(() => {
            WebSocketUtil.requestHeartBeat();
        }, 5000)
        return id;

        var self = this;
        this.heartCount = 0;
        if (this.heartInterval) {
            clearInterval(this.heartInterval);
        }
        this.heartInterval = setInterval(() => {
            self.heartCount += 1;
            if (self.heartCount > 5) {
                self.heartCount = 0;
                self.reconnection();
            }
        }, 1000);
        if (this.heartBeatTimer) {
            return this.heartBeatTimer;
        }
        else {
            return window.setInterval(function () {
                self.requestHeartBeat();
            }, 2000);
        }
    }


    /**
     * 处理网络断线重连
     */
    static reconnection() {
        return;
        var self = this;
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            if (!this.reconnectInterval) {
                var i = 0;
                this.reconnectInterval = setInterval(() => {
                    TtUtil.showWxText('断线重连中...', 1, 1000);
                    if (self.socketOpen && cc.sys.platform == cc.sys.WECHAT_GAME) {
                        wx.closeSocket();
                    }
                    self.socketOpen = false;
                    Log('断线重连中--------------')
                    setTimeout(() => {
                        WebSocketUtil.connectSocket();
                    }, 1000);
                    i += 1;
                    if (i >= 3)
                    {
                        clearInterval(self.reconnectInterval);
                        self.reconnectInterval = null;
                        TtUtil.showWxText('与服务器断开连接', 1, 2000);
                        setTimeout(()=>{
                            GameUtil.gotoSceneByPage('MainScene')
                        },1000)
                    }
                }, 3000);
            }
        }
    }
}
